#Copyright (c) 2025, Alibaba Cloud and its affiliates;
#Licensed under the Apache License, Version 2.0 (the "License");
#you may not use this file except in compliance with the License.
#You may obtain a copy of the License at

#   http://www.apache.org/licenses/LICENSE-2.0

#Unless required by applicable law or agreed to in writing, software
#distributed under the License is distributed on an "AS IS" BASIS,
#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#See the License for the specific language governing permissions and
#limitations under the License.



#!/usr/bin/env bash

kube_config=$1
namespace=$2
image_url=$3
kube_opera_dir=$4

if [ ! -f "$kube_config" ]; then
    echo "kube config file not exist!"
    kube_config = /root/.kube/config
    exit 1
fi

#kube config env
export KUBECONFIG=$kube_config

#check kuberay-operator exist
if [ ! -d "$kube_opera_dir" ]; then
    echo "kube operator dir not exist!"
    exit 1
fi

IFS=':'
read -ra image_arr <<< "$image_url"
ret=$?
if [ $ret -ne 0 ]; then
  echo "Error: operator image url analyze failed"
  exit $ret
fi
for i in "${!image_arr[@]}"; do
    echo "Element $i: ${image_arr[i]}"
done

#update image url
sed -i "s|repository:.*|repository: \"${image_arr[0]}\"|g" $kube_opera_dir/values.yaml
ret=$?
if [ $ret -ne 0 ]; then
  echo "Error: operator install update image repository failed"
  exit $ret
fi

sed -i "s/tag:.*/tag: \"${image_arr[1]}\"/g" $kube_opera_dir/values.yaml
ret=$?
if [ $ret -ne 0 ]; then
  echo "Error: operator install update image tag failed"
  exit $ret
fi

helm list -n $namespace | grep kuberay-operator
ret=$?
if [ $ret -eq 0 ]; then
  echo "Warn: kuberay-operator already exist!"
  exit $ret
fi

#install operator
helm install kuberay-operator $kube_opera_dir  -n $namespace
ret=$?
if [ $ret -ne 0 ]; then
  echo "Error: helm install operator failed"
  exit $ret
fi

: << EOF
retry_command() {
    MAX_ATTEMPTS=20
    CMD_EXIT_STATUS=1

    while [ $MAX_ATTEMPTS -gt 0 ] && [ $CMD_EXIT_STATUS -ne 0 ]; do
        "$@"
        CMD_EXIT_STATUS=$?
        sleep 1
        ((MAX_ATTEMPTS--))
    done

    if [ $CMD_EXIT_STATUS -eq 0 ]; then
        echo "Command $@ executed successfully, attempts: $((10-MAX_ATTEMPTS))."
    else
        echo "Command $@ failed even after retry attempts, last exit status: $CMD_EXIT_STATUS"
    fi
}

memory=$2
PING_TIMEOUT=120
while [ $PING_TIMEOUT -gt 0 ]; do
    ping -c 1 $1
    if [ $? -eq 0 ]; then
        break
    fi
    sleep 1
    ((PING_TIMEOUT--))
done
EOF


echo "Kube ray operator install complete!"
